package com.example.whereiamactivity;

import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.TextView;

public class WhereAmI extends Activity {

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.activity_where_am_i);
		
		LocationManager locationManager;
		String context = Context.LOCATION_SERVICE;
		
		locationManager = (LocationManager)getSystemService(context);
		
		String provider1 = LocationManager.GPS_PROVIDER;
		Location location1 = locationManager.getLastKnownLocation(provider1);
		
		updateWithNewLocation1(location1);
		
		String provider2 = LocationManager.NETWORK_PROVIDER;
		Location location2 = locationManager.getLastKnownLocation(provider2);
		
		updateWithNewLocation2(location2);
	}
	
	private void updateWithNewLocation1(Location location) {
		String latLongString;
		TextView myLocationText;
		
		myLocationText = (TextView)findViewById(R.id.myLocationText1);
		
		if (location != null) {
			double lat = location.getLatitude();
			double lng = location.getLongitude();
			latLongString = "Lat:" + lat + "\nLong:" + lng;
		}
		else{
			latLongString = "No location found";
		}
		
		myLocationText.setText("Your Current GPS Position is:\n" + latLongString);
	}

	
	private void updateWithNewLocation2(Location location) {
		String latLongString;
		TextView myLocationText;
		
		myLocationText = (TextView)findViewById(R.id.myLocationText2);
		
		if (location != null) {
			double lat = location.getLatitude();
			double lng = location.getLongitude();
			latLongString = "Lat:" + lat + "\nLong:" + lng;
		}
		else{
			latLongString = "No location found";
		}
		
		myLocationText.setText("Your Current Network Position is:\n" + latLongString);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.where_am_i, menu);
		return true;
	}
	
	
	@Override
	protected void onSaveInstanceState( Bundle outState ) {
		TextView text = (TextView)findViewById(R.id.myLocationText1);
		String message = text.getText().toString();
		
	    outState.putString("message", message);
	}
	
	@Override 
	protected void onRestoreInstanceState( Bundle savedInstanceState)
	{
		TextView text = (TextView)findViewById(R.id.myLocationText1);
		text.setText(savedInstanceState.getString("message"));
	}

}
